package com.basic.ui

import android.app.Activity
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

/**
 *
 * @author: Peter Liu
 * @date: 2023/6/19
 */

fun Fragment?.isAvailable(): Boolean {
    return this!= null && activity != null && activity!!.isAvailable() && !isDetached && !isRemoving
}
fun DialogFragment.isAvailable(): Boolean {
    return activity != null && activity!!.isAvailable() &&
            !isDetached && !isRemoving && dialog != null
}
fun Fragment.startActivityForResult(
    intent: Intent,
    onResultOk: (Intent?) -> Unit,
    onOtherResult: ((Intent?) -> Unit)? = null
) {
    val activity = activity
    if (isAvailable()) {
        val key = getStartActivityForResultKey(intent)
        if (key.isEmpty()) {
            return
        }
        val launcher = activity!!.activityResultRegistry.register(
            key,
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                onResultOk.invoke(result.data)
            } else {
                onOtherResult?.invoke(result.data)
            }
        }
        this.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                launcher.unregister()
                lifecycle.removeObserver(this)
            }
        })
        launcher.launch(intent)
    }
}